package com.example.zhu95.mytimber.adapters;

import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.zhu95.mytimber.MyApplication;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.utils.Util;

import java.io.File;
import java.io.FileFilter;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.example.zhu95.mytimber.ConstantValue.PlayMusicCmd_Play;

/**
 * @author zhu95 on 2017/12/14.
 */
public class FolderItemAdapter extends RecyclerView.Adapter<FolderItemAdapter.ViewHolder> implements SectionIndexer {

    private File[] itemFiles;
    private File currentDir = null;
    private String beforeLevelTitle = "..";
    private FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return true;
            }
            FileNameMap fileNameMap = URLConnection.getFileNameMap();
            String type = fileNameMap.getContentTypeFor(pathname.getPath());
            if (!TextUtils.isEmpty(type) && type.contains("audio/")) {
                return true;
            }
            return false;
        }
    };
    private Comparator<File> fileComparator = new Comparator<File>() {
        @Override
        public int compare(File file1, File file2) {
            if (file1.isDirectory() != file2.isDirectory()) {
                if (file1.isDirectory()) {
                    return -1;
                } else {
                    return 1;
                }
            } else {
                return file1.getName().compareToIgnoreCase(file2.getName());
            }
        }
    };

    public FolderItemAdapter(File dir) {
        getItemFiles(dir);
    }

    private void getItemFiles(File dir) {
        currentDir = dir;
        itemFiles = currentDir.listFiles(fileFilter);
        Arrays.sort(itemFiles, fileComparator);
    }

    public File getCurrentDir() {
        return currentDir;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_folder, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //首位置是 ..  返回上层
        if (position == 0) {
            holder.folderTitle.setText(beforeLevelTitle);
            holder.folderIcon.setImageResource(R.drawable.ic_folder_parent_dark);
            //返回上一层目录
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    File externalStorageDirectory = Environment.getExternalStorageDirectory();
                    if (TextUtils.equals(currentDir.getName(), externalStorageDirectory.getName())) {
                        return;
                    }
                    getItemFiles(currentDir.getParentFile());
                    FolderItemAdapter.this.notifyDataSetChanged();
                }
            });
        } else {
            final File file = itemFiles[position - 1];
            holder.folderTitle.setText(file.getName());
            //如果是文件夹
            if (file.isDirectory()) {
                holder.folderIcon.setImageResource(R.drawable.ic_folder_open_black_24dp);
                //进入目录
                holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getItemFiles(file);
                        FolderItemAdapter.this.notifyDataSetChanged();
                    }
                });
            } else {
                //是音频文件
                final SongBean song;
                //判断是否是此应用包含的音频
                if ((song = SongData.searchSong(file.getAbsolutePath())) != null) {
                    Glide.with(holder.itemView.getContext()).load(song.getAlbumArt()).centerCrop().into(holder.folderIcon);
                    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            List<SongBean> songs = new ArrayList<>();
                            for (File itemFile : itemFiles) {
                                SongBean song = SongData.searchSong(itemFile.getAbsolutePath());
                                if (song != null) {
                                    songs.add(song);
                                }
                            }
                            MyApplication.sendPlayMusicCmdBroadcast(song.getId(), Util.INSTANCE.getIdsStrFormat(songs), PlayMusicCmd_Play);
                        }
                    });
                } else {
                    holder.folderIcon.setImageResource(R.drawable.ic_file_music_dark);
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return itemFiles.length + 1;
    }

    @Override
    public Object[] getSections() {
        String[] title = new String[itemFiles.length + 1];
        title[0] = beforeLevelTitle;
        for (int i = 0; i < itemFiles.length; i++) {
            title[i + 1] = itemFiles[i].getName();
        }
        return title;
    }

    @Override
    public int getPositionForSection(int sectionIndex) {
        return sectionIndex;
    }

    @Override
    public int getSectionForPosition(int position) {
        if (position >= itemFiles.length + 1) {
            position = itemFiles.length;
        }
        return position;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.folder_icon)
        ImageView folderIcon;
        @BindView(R.id.folder_title)
        TextView folderTitle;
        @BindView(R.id.folder_item_view)
        RelativeLayout relativeLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
